import {FormState, Item} from '_types/codegenerator'

//生成mysql建表语句
export const generator_mysql_code=(form:FormState,items:Item[])=>{

    let table_column_list = '';
    let primaryKey = "";
    items.forEach((fieldObject)=>{
        let fieldLenSql="";
        //字段长度
        if(fieldObject.fieldLen){
            fieldLenSql = `(${fieldObject.fieldLen})`;
        }
        //是否为空
        let isEmptySql = "NULL";
        if(fieldObject.notEmpty){
            isEmptySql = "NOT NULL"
        }
        //默认值
        let defaultSql="";
        if(fieldObject.fieldDefult){
            defaultSql = `default ${fieldObject.fieldDefult}`
        }
        //自增
        let autoIncrementSql="";
        if(fieldObject.isAutoIncrement){
            autoIncrementSql = "AUTO_INCREMENT"
        }
        //主键
        if(fieldObject.isPrimaryKey){
            primaryKey = fieldObject.fieldName
        }
        //注释
        let fieldComment = "";
        if(fieldObject.fieldComment){
            fieldComment=` COMMENT '${fieldObject.fieldComment}'`
        }
        let field = `\`${fieldObject.fieldName}\` ${fieldObject.fieldType} ${fieldLenSql} ${isEmptySql} ${defaultSql} ${autoIncrementSql} ${fieldComment},\n`
        table_column_list+=field;
    })
    table_column_list = table_column_list.substring(0,table_column_list.length-1)

    let contentTemplate = `CREATE TABLE \`${form.tableName}\` (\n`
    contentTemplate+=`${table_column_list} \n`
    contentTemplate+=`PRIMARY KEY (\`${primaryKey}\`) ) ENGINE=InnoDB AUTO_INCREMENT=1 COMMENT = '${form.tableComment}'`;
    return contentTemplate;
}



//逆向解析


/**
 * 从一段SQL语句中解析出注释，sql格式如下：
 * @param sql  格式   COMMENT='注释'
 * @returns {string}
 */
function analysis_sql_annotation(sql){
    return sql.substring(sql.indexOf("'")+1,sql.lastIndexOf("'"));
}

/**
 * 解析默认值
 */
function analysis_sql_default(sql){
    let defaultSql = sql.substring(sql.indexOf("DEFAULT")+7).trimStart();
    debugger
    //单引号的字符串默认值
    if(defaultSql.startsWith("'")){
        if(defaultSql.indexOf("' ")>=0){
            return defaultSql.substring(1,defaultSql.indexOf("' "))
        }else{
            return defaultSql.substring(1,defaultSql.length-1)
        }
        //双引号的字符串默认值
    }else if(defaultSql.startsWith("\"")){
        if(defaultSql.indexOf("\" ")>=0){
            return defaultSql.substring(1,defaultSql.indexOf("\" "))
        }else{
            return defaultSql.substring(1,defaultSql.length-1)
        }
        //无引号的默认值，数值型
    }else{
        return defaultSql.substring(0,defaultSql.indexOf(" "))
    }
}

/**
 * 截取字符串中间的内容
 * @param code   需要截取的内容
 * @param start   开始截取点（不包含）
 * @param end    结束截取点（不包含）
 * @returns {string}
 */
function cut_start_end_out(code,start,end){
    let start_p=0;
    let end_p=code.length;
    if(start!=null){
        start_p=code.indexOf(start);
        if(start_p<0){
            start_p=0;
        }
        start_p=start_p+start.length;
    }
    if(end!=null){
        end_p=code.lastIndexOf(end);
        if(end_p<0){
            end_p=code.length;
        }
    }
    return code.substring(start_p,end_p);
}

export const generator_reverse_analysis=(sql: string) =>{
    sql=sql.trim();
    let sql_big=sql.toUpperCase();//大写sql，用来定位，取值还是取原sql
    let table_name=sql.substring(sql_big.indexOf("TABLE")+5,sql_big.indexOf("(")).trim();//表名
    if(table_name.startsWith("`")){
        table_name=table_name.substring(1,table_name.length-1);
    }
    let table_annotation=analysis_sql_annotation(sql.substring(sql_big.lastIndexOf("COMMENT")));//表注释
    let field_sql=cut_start_end_out(sql,"(",")").split(",");
    let field_array=[];//表字段
    let primaryKey="";
    field_sql.forEach(e=> {
        e = e.trim().toUpperCase();
        if (e.startsWith("PRIMARY")&&e.indexOf("KEY")>=0){
            primaryKey=e;
        }
    });
    field_sql.forEach(e=>{
        e=e.trim();
        if(e.toUpperCase().startsWith("PRIMARY KEY"))return;
        const obj:Item={
            fieldComment: "",
            fieldDefult: "",
            fieldLen: "",
            fieldName: "",
            fieldType: "",
            id: "",
            isAutoIncrement: false,
            isPrimaryKey: false,
            notEmpty: false
        };//字段对象
        //字段名
        if(e.startsWith("`")){
            e=e.substring(1);
            obj.fieldName=e.substring(0,e.indexOf("`"));
        }else{
            obj.fieldName=e.substring(0,e.indexOf(" "));
        }
        e=e.substring(e.indexOf(obj.fieldName)+obj.fieldName.length+1).trim();
        //字段注释
        let e_big=e.toUpperCase();
        let p=e_big.indexOf("COMMENT");
        if(p>-1){
            obj.fieldComment=analysis_sql_annotation(e.substring(p));
            e=e.substring(0,p).trim();
        }else{
            obj.fieldComment=obj.fieldName;
        }
        //字段类型、长度
        p=e.indexOf(")")
        if(p>-1){
            obj.fieldType=e.substring(0,e.indexOf("(")).toUpperCase();
            obj.fieldLen = e.substring(e.indexOf("(")+1,e.indexOf(")"))
        }else if(e.indexOf(" ")<0){
            obj.fieldType=e.toUpperCase();
        }else{
            obj.fieldType=e.substring(0,e.indexOf(" ")).toUpperCase();
        }
        //主键
        obj.isPrimaryKey=primaryKey.indexOf(obj.fieldName.toUpperCase())>=0;
        field_array[field_array.length]=obj;
        //默认值
        if(e_big.indexOf("DEFAULT")>0){
            obj.fieldDefult = analysis_sql_default(e)
        }
        //是否可为空
        let isEmpty = e_big.indexOf("NOT NULL")
        if(isEmpty>-1){
            obj.notEmpty = true;
        }
        //自增
        let isAutoIncrement = e_big.indexOf("AUTO_INCREMENT")
        if(isAutoIncrement>-1){
            obj.isAutoIncrement = true
        }

    });

    return {
        table_name,
        table_annotation,
        field_array
    }
}

